package com.bootemp.common;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(value = "/admin/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //处理请求和响应
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        //处理session
        HttpSession session=req.getSession();
        Object obj=session.getAttribute("admin");
        if (obj!=null){
            //放行资源
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            //重定向到登录页面
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
